<?php


namespace App\Job;


use App\Utils\LusScript;
use Predis\Client;

class RedisQueue implements QueueContract
{
    public $redis;

    public function __construct()
    {
        $this->redis = new Client([
            'scheme' => 'tcp',
            'host' => 'redis',
            'port' => 6379
        ]);
//        $this->redis->select(0);
    }


    public function dispatch($key, IJob $job)
    {
        $this->redis->rpush($key, json_encode([
            'job' => serialize($job),
            'attempts' => 0
        ]));
    }

    public function dequeue($queue)
    {
        list($job, $reserved) = $this->redis->eval(
            LusScript::pop(), 2, $queue, $queue . ':reserved',
            time()
        );
        if ($reserved) {
            return new RedisJob($this->redis, $job, $queue, $reserved);
        }
        return null;
    }
}